package com.guojiang.guopicturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guojiang.guopicturebackend.constant.UserConstant;
import com.guojiang.guopicturebackend.exception.BusinessException;
import com.guojiang.guopicturebackend.exception.ErrorCode;
import com.guojiang.guopicturebackend.exception.ThrowUtils;
import com.guojiang.guopicturebackend.manager.auth.StpKit;
import com.guojiang.guopicturebackend.model.dto.user.UserQueryRequest;
import com.guojiang.guopicturebackend.model.entity.User;
import com.guojiang.guopicturebackend.model.enums.UserRoleEnum;
import com.guojiang.guopicturebackend.model.vo.user.LoginMaskedUserVO;
import com.guojiang.guopicturebackend.model.vo.user.MaskedUserVO;
import com.guojiang.guopicturebackend.service.UserService;
import com.guojiang.guopicturebackend.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 过江辉
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2025-01-05 22:47:11
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 用户注册
     *
     * @param userAccount
     * @param userPassword
     * @param checkPassword
     * @return
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验参数
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入密码不一致");
        }
        // 2. 检查用户账号是否和数据库中已有的重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 3. 密码一定要加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 4. 插入数据到数据库中
        User newUser = new User();
        newUser.setUserAccount(userAccount);
        newUser.setUserPassword(encryptPassword);
        newUser.setUserName("未设置昵称");
        newUser.setUserRole(UserRoleEnum.USER.getValue());
        boolean saveResult = this.save(newUser);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }
        return newUser.getId();
    }

    /**
     * 获得加密密码
     *
     * @param userPassword
     * @return 加密后的密码
     */
    @Override
    public String getEncryptPassword(String userPassword) {
        // 加盐，混淆密码
        final String SALT = "guoTuTuUltraMan";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    /**
     * 用户登录
     *
     * @param userAccount
     * @param userPassword
     * @param request
     * @return 脱敏后的用户信息
     */
    @Override
    public LoginMaskedUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验参数
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 2. 对用户传递的密码进行加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 3. 查询数据库中用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 先查询用户是否存在
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User loginUser = userMapper.selectOne(queryWrapper);
        if (loginUser == null) {
            log.info("The user does not exist or wrong userPassword");
            throw new BusinessException(ErrorCode.NULL_ERROR, "用户不存在或密码错误");
        }
        // 4. 保存用户登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, loginUser);
        // 同时要记录用户登录态到 Sa-Token，便于空间鉴权的时候使用
        StpKit.SPACE.login(loginUser.getId());
        StpKit.SPACE.getSession().set(UserConstant.USER_LOGIN_STATE, loginUser);
        return this.getLoginMaskedUserVO(loginUser);
    }

    /**
     * 获取当前登录用户脱敏信息
     *
     * @param user
     * @return 脱敏后的当前登录用户信息
     */
    @Override
    public LoginMaskedUserVO getLoginMaskedUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginMaskedUserVO loginMaskedUserVO = new LoginMaskedUserVO();
        BeanUtils.copyProperties(user, loginMaskedUserVO);
        return loginMaskedUserVO;
    }

    /**
     * 获取脱敏用户信息
     *
     * @param user
     * @return 脱敏后的用户信息
     */
    @Override
    public MaskedUserVO getMaskedUserVO(User user) {
        if (user == null) {
            return null;
        }
        MaskedUserVO maskedUserVO = new MaskedUserVO();
        BeanUtils.copyProperties(user, maskedUserVO);
        return maskedUserVO;
    }

    /**
     * 获取脱敏用户信息列表
     *
     * @param userList
     * @return 脱敏后的用户信息列表
     */
    @Override
    public List<MaskedUserVO> getMaskedUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream()
                .map(this::getMaskedUserVO)
                .collect(Collectors.toList());
    }

    /**
     * 获取当前登录用户（后端内部使用）
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 1. 判断是否登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        // 2. 如果getAttribute后userObj为空表示未登录
        User currentUser = (User) userObj;
        ThrowUtils.throwIf(currentUser == null || currentUser.getId() == null, ErrorCode.NOT_LOGIN);
        // 从数据库查询，保证数据一致性（追求性能这段可以注释）
        currentUser = this.getById(currentUser.getId());
        ThrowUtils.throwIf(currentUser == null, ErrorCode.NOT_LOGIN);
        return currentUser;
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 判断是否登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        // 未登录无法登出
        ThrowUtils.throwIf(userObj == null, ErrorCode.OPERATION_ERROR, "未登录无法登出");
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }


    /**
     * 获取用户查询对象
     *
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR, "userQueryRequest 为空");
        // 取出查询的属性
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userAccount = userQueryRequest.getUserAccount();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        String searchText = userQueryRequest.getSearchText();
        // 创建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 从多字段中搜索  
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件  
            queryWrapper.and(qw -> qw.like("userName", searchText)
                    .or()
                    .like("userProfile", searchText)
            );
        }
        // 根据 Id、权限 精确查询
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        // 根据 用户昵称、账号、个性签名 模糊匹配
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        // 设定排序字段和排序顺序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 判断用户是否是管理员
     *
     * @param user
     * @return
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }
}




